package com.noble.glamour.ui.agora.act.voice;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.bean.center.user.light.UserLight;
import com.noble.glamour.bean.center.user.light.UserLightList;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.baseui.custom.CountDownTextView;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.webserver.WebService;
import com.noble.glamour.module.logic.webserver.WebServiceConfig;
import com.noble.library.utils.UIUtil;
import com.noble.glamour.module.util.WebUtil;
import com.noble.glamour.ui.agora.act.base.RtcBaseActivity;
import com.noble.glamour.ui.agora.act.base.RtcWebPanel;
import com.noble.glamour.ui.agora.act.bean.ChatStatus;
import com.noble.glamour.ui.agora.act.bean.RtcGiftList;
import com.noble.glamour.ui.agora.manager.RtcMessageMgr;
import com.noble.glamour.ui.agora.model.AgoraConstant;
import com.noble.glamour.ui.agora.util.RtcJointChannel;
import com.noble.glamour.ui.agora.util.RtcTimerUtil;
import com.noble.glamour.ui.agora.view.RtcGiftInfoView;
import com.noble.glamour.ui.utils.NoDoubleClickListener;
import com.noble.library.image.ImageLoader;
import com.noble.library.log.PToast;
import com.noble.library.observe.Msg;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.view.roadlights.LMarqueeFactory;
import com.noble.library.view.roadlights.LMarqueeView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 女性任务版: 语音接通界面
 * Created by Su on 2017/6/19.
 */
public class RtcVoiceActivity extends RtcBaseActivity implements PObserver, RequestComplete {
    private RelativeLayout rootView;
    private LinearLayout msgTipsLayout;      // 钻石不足提示消息
    private LinearLayout functionPanel;      // 底部功能按钮
    private CountDownTextView tipsCountDown; // 钻石不足提示倒计时
    private TextView tvEarn;                 // 女号聊天收入
    private ImageView imgBg, imgHead;
    private LMarqueeView lMarqueeView;
    private LMarqueeFactory<LinearLayout, RtcGiftList.GiftInfo> marqueeView;

    // 聊天数据
    private UserLight infoLight;

    private RtcWebPanel webPanel;
    private LinearLayout rotaryPanel;       // H5大转盘
    private RtcVoiceFootPanel footPanel;
    private int lastHeight = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        rootView = (RelativeLayout) getLayoutInflater().inflate(R.layout.p1_chat_voice, null);
        setContentView(rootView);
        initView();
        addListener();
        addGlobalListener();
    }

    private void addListener() {
        if (RtcMessageMgr.getInstance().leaveChat()) {
            finish();
            PToast.showLong(getString(R.string.chat_tips_user_hangup));
            return;
        }
        MsgMgr.getInstance().attach(this);
    }

    private void addGlobalListener() {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (isFinishing()) return;
                Rect r = new Rect();
                //获取当前界面可视部分
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;

                //键盘收起,弹出
                if (heightDifference == 0 && lastHeight > 0) {
                    functionPanel.setTranslationY(0);
                    footPanel.refreshLayout();
                } else if (heightDifference > 0) {
                    functionPanel.setTranslationY(-heightDifference);
                }
                lastHeight = heightDifference;
            }
        });
    }

    private void initView() {
        WebService.getInstance().StartWebServiceForSDCard();   // 启动WebService
        functionPanel = (LinearLayout) findViewById(R.id.chat_faction_panel);
        imgBg = (ImageView) findViewById(R.id.iv_bg);
        Bitmap bitmap = BitmapUtil.getDecodeBitmap(this, R.drawable.p1_default_bg, 320, 480);
        UIUtil.setBackground(imgBg, new BitmapDrawable(null, bitmap));
        imgHead = (ImageView) findViewById(R.id.iv_head);

        // 底部功能按键
        footPanel = new RtcVoiceFootPanel(this);
        functionPanel.addView(footPanel.getContentView());

        // 礼物跑马灯
        lMarqueeView = (LMarqueeView) findViewById(R.id.rtc_chat_marquee);
        marqueeView = new RtcGiftInfoView(this);

        if (!ModuleMgr.getCenterMgr().getMyInfo().isMan()) {
            LinearLayout ll_earn = (LinearLayout) findViewById(R.id.ll_earn);
            tvEarn = (TextView) findViewById(R.id.tv_earn);
            ll_earn.setVisibility(View.VISIBLE);
            tvEarn.setText(getString(R.string.chat_video_girl_earn, config().mGirlEarn));
        }

        // 男性显示余额计时
        if (ModuleMgr.getCenterMgr().getMyInfo().isMan()) {
            // 计时控件
            initCountDownTimer();
        }

        Chronometer chatTime = (Chronometer) findViewById(R.id.ch_count_time);
        chatTime.setBase(SystemClock.elapsedRealtime() - config().millisPass);
        RtcTimerUtil.getInstance().addTimer(chatTime);
        chatTime.start();

        findViewById(R.id.btn_hanging_up).setOnClickListener(listener);
        findViewById(R.id.iv_shrink_narrow).setOnClickListener(listener);

        verControl();
        ModuleMgr.getRtcEnginMgr().setVideoChat(true);// 设置用户音频聊天状态
        RtcJointChannel.getInstance().reqUserInfo(this);
        ModuleMgr.getRtcEnginMgr().reqGiftBanner(this);  // 获取跑马灯礼物
        if (!config().mHasJoin) {
            ModuleMgr.getRtcEnginMgr().joinChannel(config().mChannel);
            config().mHasJoin = true;
        }
    }

    /**
     * 版本控制界面展示
     */
    private void verControl() {
        rotaryPanel = (LinearLayout) findViewById(R.id.chat_rotary_panel);
        if (config().msgVer < AgoraConstant.RTC_MSG_VER) {
            rotaryPanel.setVisibility(View.GONE);
            return;
        }

        // H5容器
        HashMap<String, Object> rotaryParams = new HashMap<>();
        rotaryParams.put("view_type", 1);
        String rotaryUrl = WebUtil.jointUrl(WebServiceConfig.reqVideoWebRotary.getUrl(), rotaryParams);
        webPanel = new RtcWebPanel(this, rotaryUrl);
        rotaryPanel.addView(webPanel.getContentView());
    }

    private void initCountDownTimer() {
        msgTipsLayout = (LinearLayout) findViewById(R.id.msg_tips);
        tipsCountDown = (CountDownTextView) findViewById(R.id.tv_countDown);
        RtcTimerUtil.getInstance().addTimer(tipsCountDown);
        TextView tipsTxt = (TextView) findViewById(R.id.time_left_tips);

        // 女号都是邀请流程，扣费方全部为男方扣费
        if (!ModuleMgr.getCenterMgr().getMyInfo().isMan())
            tipsTxt.setText(getString(R.string.chat_tips_other_no_diamond));

        if (config().millisLeft > 0 && config().millisLeft <= AgoraConstant.CHAT_COST_PROMPT) {
            msgTipsLayout.setVisibility(View.VISIBLE);
            tipsCountDown.setCountDownTimes(config().millisLeft * 1000);
            tipsCountDown.start();
        }
    }

    /**
     * 点击事件
     */
    private NoDoubleClickListener listener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.btn_hanging_up:      // 通话过程中挂断按钮
                    RtcJointChannel.getInstance().stopChat();
                    break;

                case R.id.iv_shrink_narrow: // 最小化
                    if (checkOverLaysPermission())
                        ModuleMgr.getRtcEnginMgr().startRtcFloatService();
                    break;
            }
        }
    };

    /**
     * 通话状态消息：由主Apk传递状态值
     */
    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Rtc_Chat_Status:
                Map<String, Object> data = (Map<String, Object>) value;
                switch ((int) data.get("type")) {
                    case 3:
                    case 4:     // 挂断
                        PToast.showShort(getString(R.string.chat_tips_hangup));
                        finish();
                        break;
                    default:
                        break;
                }
                break;

            case MsgType.MT_Rtc_Chat_Connect_Suc:
                LoadingDialog.closeLoadingDialog();
                break;

            case MsgType.MT_Rtc_Check_Video_Chat:
                ChatStatus chatStatus = (ChatStatus) value;
                if (ModuleMgr.getCenterMgr().getMyInfo().isMan() || chatStatus.getTotalIncome() <= 0)
                    return;
                tvEarn.setText(getString(R.string.chat_video_girl_earn, config().mGirlEarn));
                break;

            case MsgType.MT_Rtc_Chat_Close_Msg:
                finish();
                break;

            case MsgType.MT_Rtc_Chat_Timer_Msg:
                if (!ModuleMgr.getCenterMgr().getMyInfo().isMan()) return;
                if ((int) value == AgoraConstant.TIMER_LAST_TIPS) {
                    msgTipsLayout.setVisibility(View.VISIBLE);
                    tipsCountDown.setCountDownTimes(config().millisLeft * 1000);
                    tipsCountDown.start();
                }
                break;

            case MsgType.MT_Rtc_Chat_Switch_Micro:
                footPanel.refreshSwitchMicro((Boolean) value);
                break;

            case MsgType.MT_Chat_Can:
                if (ModuleMgr.getCenterMgr().getMyInfo().isMan() && !ModuleMgr.getCenterMgr().getMyInfo().isVip()) {//男
                    footPanel.refreshChatBtn((Boolean) ((Msg) value).getData());
                }
                break;
        }
    }

    /**
     * 个人信息请求结果回调
     */
    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqUserInfoSummary) {
            if (!response.isOk()) return;
            UserLightList list = (UserLightList) response.getBaseData();
            if (list.getLightList() != null && list.getLightList().size() > 0) {
                infoLight = list.getLightList().get(0);
                // 更新布局
                ImageLoader.loadBlur(this, infoLight.getAvatar(), imgBg, 8, R.drawable.p1_default_bg);
                ImageLoader.loadRoundAvatar(this, infoLight.getAvatar(), imgHead);
                ((TextView) findViewById(R.id.tv_name)).setText(infoLight.getNickname());
//                findViewById(R.id.iv_vip_status).setVisibility(infoLight.isVip() ? View.VISIBLE : View.GONE);
                ModuleMgr.getRtcEnginMgr().getEngineConfig().nickname = infoLight.getNickname();
            }
            return;
        }

        if (response.getUrlParam() == UrlParam.reqGiftBanner) {
            if (!response.isOk()) return;
            RtcGiftList list = (RtcGiftList) response.getBaseData();
            List<RtcGiftList.GiftInfo> giftList = list.getGiftList();
            if (giftList != null && !giftList.isEmpty()) {
                lMarqueeView.setVisibility(View.VISIBLE);
                marqueeView.setData(ModuleMgr.getRtcEnginMgr().removeInvalidGift(giftList));
                lMarqueeView.setAnimInAndOut(R.anim.top_in, R.anim.bottom_out);
                lMarqueeView.setMarqueeFactory(marqueeView);
                lMarqueeView.startFlipping();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webPanel != null) {
            webPanel.getWebView().onResume();
            webPanel.getWebView().resumeTimers();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webPanel != null) {
            webPanel.getWebView().onPause();
            webPanel.getWebView().pauseTimers();
        }
    }

    private void releaseWebView() {
        if (webPanel != null)
            webPanel.clearReference();
        if (rotaryPanel != null)
            rotaryPanel.removeAllViews();
        webPanel = null;
        rotaryPanel = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseWebView();
    }

    @Override
    public void finish() {
        super.finish();
        LoadingDialog.closeLoadingDialog();
        MsgMgr.getInstance().detach(this);
        ModuleMgr.getRtcEnginMgr().setVideoChat(false);     // 音频中收发消息

        // 处于悬浮窗， 则只需释放本地Timer计时
        if (RtcJointChannel.getInstance().getFloatStatus()) {
            ModuleMgr.getRtcEnginMgr().releaseLocalTimer();
            return;
        }

        // 全部回收
        config().mHasJoin = false;
        WebService.getInstance().stop();
        RtcJointChannel.getInstance().resetSwitchMicro();
        ModuleMgr.getRtcEnginMgr().releaseAll();
    }
}
